package top.luoyuanxiang.mqtt.utils;

import java.util.Arrays;

public class Escape_0x7e {
	/**
	 * 十六进制框架标志
	 */
	public static final String HEX_FRAME_FLAG = "7E";
	private static final String HEX_FRAME_ESC = "7D";
	private static final String HEX_FRAME_01 = "01";
	private static final String HEX_FRAME_02 = "02";

	public static void main(String[] args) {


		byte[] in = {0x30, 0x7e, 0x08, 0x7d, 0x55 };
		// 转成大写字母
		String hexStr = Jtt808Utils.byte2HexToUpperCase(in);
		System.out.println("原文：" + hexStr);
		hexStr = encode(hexStr);
		System.out.println("转义后：" + hexStr);
		hexStr = decode(hexStr);
		System.out.println("反转义后：" + hexStr);
		byte[] out = Jtt808Utils.hex2byte(hexStr);

		System.out.println("10进制：" + Arrays.toString(out));
		System.out.print("转成16进制：");
		for (int i = 0; i < out.length; i++) {
			System.out.print( Integer.toHexString(out[i]) + ",");
		}
		System.out.print("");
	}

	/**
	 * 标识位采用0x7e 表示，若校验码、消息头以及消息体中出现0x7e, 则要进行转义处理，转义规则定 义如下：
	 * ——0x7e₄→0x7d  后紧跟一个0x01;
	 * ——0x7d₄→0x7d 后紧跟一个0x02;
	 * @param hexStr
	 * @return hexStr
	 */
	public static String encode(String hexStr) {
		hexStr = hexStr.toUpperCase();
		hexStr = hexStr.replaceAll(HEX_FRAME_ESC, HEX_FRAME_ESC + HEX_FRAME_02);
		return hexStr.replaceAll(HEX_FRAME_FLAG, HEX_FRAME_ESC + HEX_FRAME_01);
	}

	public static String decode(String escapeHexStr) {
		escapeHexStr = escapeHexStr.toUpperCase();
		escapeHexStr = escapeHexStr.replaceAll(HEX_FRAME_ESC + HEX_FRAME_01, HEX_FRAME_FLAG);
		return escapeHexStr.replaceAll(HEX_FRAME_ESC + HEX_FRAME_02, HEX_FRAME_ESC);
	}
}
